<template>
  <div class="add-payslip" style="padding-top: 0">
    <PageHeader @back="$router.go(-1)" subTitle="返回"> </PageHeader>

    <a-row class="content-top">
      <step :current="0" />
    </a-row>
    <div v-if="!salary.length" class="addPayslip-middle">
      <a-row class="content-con">
        <div style="display: flex; justify-content: center">
          <xq-icon type="icon-jilu" class="primary_color w32 mr14" style="font-size: 30px" />
          <h2 class="title"><span v-if="pageState === '2'">同步</span><span v-if="pageState === '1'">上传</span>月工资列表</h2>
        </div>
        <h3 class="sub_tit">系统自动识别您的工资表，通过短信和微信一键发送给员工</h3>
        <a-form layout="inline" class="form" :form="form">
          <a-row>
            <a-form-item class="form-item" label="请选择月份">
              <a-month-picker
                :allowClear="false"
                v-model="selectDate"
                format="YYYY-MM"
                style="width: 300px"
                placeholder="请选择"
                @change="getMonthlySalaryList"
              />
            </a-form-item>
          </a-row>
          <a-row>
            <a-form-item class="form-item" label="工资表名称" v-if="pageState === '1'">
              <a-input v-model="tableName" placeholder="最多20字" style="width: 300px" :max-length="20" />
            </a-form-item>
          </a-row>
          <a-row>
            <a-form-item class="form-item" label="工资表模板" v-if="pageState === '2' && dataList.length">
              <a-select allowClear label-in-value placeholder="请选择工资表模板" style="width: 300px" @change="selectChange">
                <a-select-option v-model="item.id" v-for="(item, index) in dataList" :key="index">
                  {{ item.name }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-row>
          <a-row>
            <a-form-item class="form-item" label="工资表明细" v-if="tableName && pageState === '2' && dataList.length">
              <a-select
                v-model="itemsLstSelected"
                :options="itemsLst"
                mode="multiple"
                placeholder="请选择工资表模板"
                style="width: 300px"
              />
            </a-form-item>
          </a-row>
          <a-form-item>
            <a-upload :action="action" @change="cbUpload" v-if="pageState === '1'">
              <a-button ref="onUpload" type="primary" :disabled="disabled" @click="onUpload">导入月工资表 </a-button>
            </a-upload>
            <a-button
              v-if="pageState === '2'"
              style="width: 300px; margin-left: 100px"
              ref="onUpload"
              type="primary"
              :disabled="disabled"
              @click="generateWage"
              >下一步
            </a-button>
          </a-form-item>
        </a-form>
      </a-row>
      <a-row class="content-foot" v-if="pageState !== '2'">
        <h2>温馨提示</h2>

        <div class="sub_tit">
          导入遇到问题? 请使用标准模版
          <span class="primary">
            <a @click="downLoad">下载标准模板</a>
          </span>
        </div>
      </a-row>
    </div>
    <template v-else>
      <a-row class="salary" type="flex" align="middle" justify="space-between">
        <a-col class="item" :span="9">
          <a-row type="flex" align="middle" justify="space-between">
            <a-col :span="8" @click="selectItem">
              <a-row>
                <strong class="primary">总共</strong>
              </a-row>
              <a-row class="primary">{{ titles.countAll }}</a-row>
            </a-col>
            <a-divider style="height: 42px" type="vertical" />
            <a-col :span="6" @click="selectItem">
              <a-row>
                <strong class="sub_tit">企业员工</strong>
              </a-row>
              <a-row>{{ titles.countInCompany }}</a-row>
            </a-col>
            <a-col :span="6" @click="selectItem">
              <a-row>
                <strong class="sub_tit">非企业员工</strong>
              </a-row>
              <a-row>{{ titles.countNotInCompany }}</a-row>
            </a-col>
          </a-row>
        </a-col>
        <a-col class="item" :span="7">
          <a-row type="flex" align="middle" justify="space-between">
            <a-col :span="8" @click="selectItem">
              <a-row>
                <strong class="sub_tit">微信绑定</strong>
              </a-row>
              <a-row>{{ titles.countWeChatBind }}</a-row>
            </a-col>
            <a-divider style="height: 42px" type="vertical" />
            <a-col :span="6" @click="selectItem">
              <a-row>
                <strong class="sub_tit">微信未绑定</strong>
              </a-row>
              <a-row>{{ titles.countWeChatUnBind }}</a-row>
            </a-col>
          </a-row>
        </a-col>
        <a-col class="item" :span="7">
          <a-row type="flex" align="middle" justify="space-between">
            <a-col :span="8">
              <a-row>
                <strong class="sub_tit">应发工资</strong>
              </a-row>
              <a-row>{{ titles.sumSalaryAmount }}</a-row>
            </a-col>
            <a-divider style="height: 42px" type="vertical" />
            <a-col :span="6">
              <a-row>
                <strong class="sub_tit">实发工资</strong>
              </a-row>
              <a-row>{{ titles.sumSalaryReal }}</a-row>
            </a-col>
          </a-row>
        </a-col>
      </a-row>
      <a-table
        :scroll="{ x: 1500 }"
        :columns="columns"
        class="mg_t24"
        list-type="picture"
        :pagination="pagination"
        :data-source="salary"
        @change="handlePage"
      >
        <template slot="empInCompany" slot-scope="empInCompany">
          <img v-if="!empInCompany" src="@/assets/img/payslip/weixuanzhong.png" />
          <img v-if="empInCompany" src="@/assets/img/payslip/xuanzhong.png" />
        </template>
        <template slot="phoneStatus" slot-scope="phoneStatus">
          <img v-if="!phoneStatus" src="@/assets/img/payslip/weixuanzhong.png" />
          <img v-if="phoneStatus" src="@/assets/img/payslip/xuanzhong.png" />
        </template>
        <template slot="wechatStatus" slot-scope="wechatStatus">
          <img v-if="!wechatStatus" src="@/assets/img/payslip/weixuanzhong.png" />
          <img v-if="wechatStatus" src="@/assets/img/payslip/weixin.png" />
        </template>
      </a-table>
    </template>
    <excelCalback v-if="excelVisible" :visible="excelVisible" :options="excelOptions" @change="excelChange" />
    <a-row v-if="salary.length" class="mg_t24" type="flex" justify="end">
      <a-button class="mg_r12" @click="reUpload">重新上传</a-button>
      <a-button type="primary" @click="next">下一步</a-button>
    </a-row>
  </div>
</template>

<script>
import moment from "moment";
import { mapState, mapMutations, mapGetters } from "vuex";
import { getMonthlySalary, generateWageList } from "@/api/wages/monthly";
import ExportMixin from "xqjr-plugin-common/UploadOrExport/exportMixin";
import axios from "axios";
import qs from "qs";
const mixin = new ExportMixin();
export default {
  mixins: [mixin],
  name: "AddPayslip",
  components: {
    step: () => import("./step"),
    excelCalback: () => import("./excel-calback")
  },

  data() {
    return {
      salaryTemplateId: null,
      monthly: null,
      yearly: null,
      dataList: [],
      pageState: this.$route.query.item,
      selectDate: undefined,
      tableName: undefined,
      tableName2: "",
      action: "",
      columns: [
        {
          key: "empName",
          title: "姓名",
          width: 150,
          dataIndex: "empName",
          fixed: "left"
        },
        {
          title: "企业员工",
          key: "empInCompany",
          dataIndex: "empInCompany",
          width: 150,
          scopedSlots: { customRender: "empInCompany" }
        },
        {
          title: "手机",
          dataIndex: "phoneStatus",
          key: "phoneStatus",
          width: 150,
          scopedSlots: { customRender: "phoneStatus" }
        },
        {
          title: "微信",
          dataIndex: "wechatStatus",
          key: "wechatStatus",

          width: 150,
          scopedSlots: { customRender: "wechatStatus" }
        },
        {
          title: "手机号",
          dataIndex: "phone",
          key: "phone",

          width: 150
        },
        {
          title: "基本工资",
          dataIndex: "salaryBasic",
          key: "salaryBasic",

          width: 150
        },
        {
          title: "个人社保",
          dataIndex: "empSoc",
          key: "empSoc",
          width: 150
        },
        {
          title: "实发工资",
          dataIndex: "salaryReal",
          key: "salaryReal",
          width: 150
        }
      ],
      titles: {},
      cbParams: {
        pageNo: 1,
        reloadCount: true,
        pageSize: 10
      },
      pagination: {
        pageSize: 10,
        current: 1,
        total: 0
      },
      salary: [],
      excelVisible: false,
      excelOptions: {},
      hide: false,
      form: this.$form.createForm(this, { name: "coordinated" }),
      params: {
        month: "",
        year: "",
        tableName: ""
      },
      tableId: "",
      itemsLst: [],
      itemsLstSelected: []
    };
  },
  computed: {
    ...mapState(["hr"]),
    ...mapGetters({ PAYSLIP: "wages/PAYSLIP" }),
    disabled() {
      return !(this.tableName !== undefined && this.selectDate !== undefined);
    }
  },

  methods: {
    loadItems() {
      this.$request({
        url: `/salary/api/v1/salaryTemplateSalaries/selectByHeaderListId?salaryTemplateSalaryId=${this.salaryTemplateId}`
      })
        .then((res) => {
          this.itemsLstSelected = res.data;
          this.itemsLst = res.data.map((item) => ({
            label: item,
            value: item,
            disabled: item === "实发工资" || item === "应发工资"
          }));
        })
        .catch(() => {});
    },
    selectChange(e) {
      this.salaryTemplateId = e.key;
      this.tableName = e.label;
      this.loadItems();
    },
    generateWage() {
      generateWageList({
        companyId: this.hr.companyId,
        monthly: this.monthly,
        salaryTemplateSalaryId: parseInt(this.salaryTemplateId),
        yearly: this.yearly,
        tableName: this.tableName,
        itemNameList: this.itemsLstSelected
      }).then((res) => {
        // localStorage.setItem("tempWagePayroll", JSON.stringify(this.itemsLstSelected));
        this.tableId = res.data;
        this.excelChange();
      });
    },
    getMonthlySalaryList(e) {
      this.dataList = [];
      this.tableName = undefined;
      this.monthly = moment(e).format("MM");
      this.yearly = moment(e).format("YYYY");
      if (this.pageState === "2") {
        getMonthlySalary({
          companyId: this.hr.companyId,
          monthly: this.monthly,
          yearly: this.yearly,
          pageNo: 1,
          pageSize: 100
        }).then((res) => {
          this.dataList = res.data.entities;
        });
      }
    },
    ...mapMutations({
      getSuccessList: "wages/successList",
      cbData: "wages/cbData",
      tableIds: "wages/tableId",
      postParams: "wages/postParams",
      resetPostParams: "wages/resetPostParams"
    }),
    // 导入工资表
    onUpload() {
      const [year, month] = this.selectDate.format("YYYY-MM").split("-");
      this.action = `/hr/api/v1/salaryBills/import?companyId=${this.hr.companyId}&month=${month}&year=${year}&tableName=${this.tableName}`;
      this.params.year = year;
      this.params.month = month;
    },
    cbUpload(e) {
      if (e.file) {
        if (e.file.response && e.file.response.data) {
          const data = e.file.response.data;
          this.tableId = data.tableId;
          const { response } = e.file;
          if (response && response.data && response.data) {
            this.onUploadChange(response.data);
          }
        } else {
          if (e.file.response && e.file.response.msg) {
            this.$notification["error"]({ message: e.file.response.msg });
          }
        }
      }
    },
    onUploadChange(data) {
      this.excelVisible = true;
      this.excelOptions = data;
      this.tableId = data.tableId;
    },
    // 上传成功的excel
    successExcel() {
      this.$request({
        url: `/hr/api/v1/salaryBills/pageRelation`,
        params: {
          companyId: this.hr.companyId,
          tableId: this.tableId,
          ...this.cbParams,
          pageSize: this.pagination.pageSize
        }
      }).then(({ data }) => {
        //  this.cbData(data);
        this.titles = {
          countAll: data.countAll,
          countInCompany: data.countInCompany,
          countNotInCompany: data.countNotInCompany,
          countWeChatBind: data.countWeChatBind,
          countWeChatUnBind: data.countWeChatUnBind,
          sumSalaryAmount: data.sumSalaryAmount,
          sumSalaryReal: data.sumSalaryReal
        };
        this.salary = data.salaryBillListVOPage.entities || [];
        // this.getSuccessList(this.salary);
        this.pagination.total = data.salaryBillListVOPage.entityCount || 0;
        this.salary.forEach((item) => {
          item.salaryBillFieldsDOList.forEach((key) => {
            key.dataIndex = key.sort;
          });
        });
        const colum = [];
        this.salary[0].salaryBillFieldsDOList.map((key) => {
          colum.push({
            dataIndex: key.sort,
            title: key.fieldName,
            width: 150,
            key: key.sort
          });
        });
        this.salary = this.salary.map((item) => {
          const obj = {};
          item.salaryBillFieldsDOList.map((key) => {
            obj[key["dataIndex"]] = key["fieldValue"];
          });
          item = { ...item, ...obj };
          return item;
        });
        this.columns = [...this.columns, ...colum];
      });
    },
    // excelCalback
    excelChange(e) {
      if (e && e.visibleWrong) {
        this.excelVisible = e.visibleWrong;
      } else {
        this.excelVisible = false;
        this.$router.push({
          path: "add-payslip-sort",
          query: {
            tableId: this.tableId,
            month: this.monthly,
            year: this.yearly,
            sendName: this.tableName
          }
        });
      }
    },
    // 下载模板
    // downLoad() {
    //   const link = document.createElement("a");
    //   const MIME_TYPE = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
    //   link.download = "工资导入模板";
    //   link.href =
    //     "https://hjrl-public.oss-cn-qingdao.aliyuncs.com/excel_template/emp_info/salaryBill/%E4%B8%8A%E4%BC%A0%E5%B7%A5%E8%B5%84%E8%A1%A8%E6%A8%A1%E7%89%88-.xlsx";
    //   link.dataset.downloadurl = [MIME_TYPE, link.download, link.href].join(":");
    //   document.body.appendChild(link);
    //   link.click();
    //   document.body.removeChild(link);
    // },
    downLoad() {
      const token = this.$store.state.auth.token;
      let params = {};
      params = {
        templateName: "electronicPayrollTemplate.xlsx"
      };

      axios({
        url: `/hr/api/v1/excel/template/download`,
        params,
        paramsSerializer: (param) => {
          return qs.stringify(param, { indices: false });
        },
        method: "get",
        responseType: "blob",
        headers: {
          token: token
        }
      })
        .then((res) => {
          const link = document.createElement("a");
          const blob = new Blob([res.data], {
            type: "multipart/form-data"
          });
          link.style.display = "none";
          link.href = URL.createObjectURL(blob);
          link.setAttribute("download", "上传工资表模板.xlsx");
          document.body.appendChild(link);
          link.click();
          document.body.removeChild(link);
        })
        .catch((err) => {
          console.log("debug log --> ", err);
        });
    },
    // 表单提交
    handleSubmit(e) {
      this.form.validateFields((err, values) => {
        if (!err) {
          values.selectDate = values.selectDate.format("YYYY-MM");
          this.params.tableName = values.tableName;
          this.params.year = values.selectDate.split("-")[0];
          this.params.month = values.selectDate.split("-")[1];
          this.hide = !this.hide;
          this.postParams({
            sendName: values.tableName,
            month: this.params.month,
            year: this.params.year
          });
        }
      });
    },
    // 重新上传
    reUpload() {
      this.salary = [];
      this.tableName = undefined;
      this.selectDate = undefined;
    },

    // 翻页
    handlePage(e) {
      this.pagination.current = e.current;
      this.cbParams.pageNo = e.current;

      this.$request({
        url: `/hr/api/v1/salaryBills/pageRelation`,
        params: {
          companyId: this.hr.companyId,
          tableId: this.tableId,
          ...this.cbParams
        }
      }).then(({ data }) => {
        this.titles = {
          countAll: data.countAll,
          countInCompany: data.countInCompany,
          countNotInCompany: data.countNotInCompany,
          countWeChatBind: data.countWeChatBind,
          countWeChatUnBind: data.countWeChatUnBind,
          sumSalaryAmount: data.sumSalaryAmount,
          sumSalaryReal: data.sumSalaryReal
        };
        this.salary = data.salaryBillListVOPage.entities || [];
        this.pagination.total = data.salaryBillListVOPage.entityCount || 0;
        this.getSuccessList(this.salary);
      });
    },

    // 下一页
    next() {
      this.$router.push({
        path: "/wages/add-payslip-second",
        query: {
          unSendCount: this.pagination.total
        }
      });
    },
    // 筛选
    selectItem(type) {}
  }
};
</script>
<style lang="scss" scoped>
.add-payslip {
  padding: 24px;
  .addPayslip-middle {
    .content-con {
      // background-image: url(~@/assets/img/wageMonthBg.png);
      background-size: 100% 100%;
    }
  }
  .content-top {
    margin-top: 24px;
    padding: 40px 162px;
    background: #ffffff;
    box-shadow: 0px 4px 12px 0px var(--primary10);
    border-radius: 4px;
  }
  .content-con {
    text-align: center;
    margin-top: 24px;
    padding: 40px 162px;
    background: #ffffff;
    box-shadow: 0px 4px 12px 0px var(--primary10);
    border-radius: 4px;
    ::v-deep.form {
      text-align: center;
      .form-item {
        margin: 12px 0;
        text-align: left;
      }
    }
  }
  .content-foot {
    margin-top: 24px;
    padding: 24px;
    background: #fafafa;
    border-radius: 4px;
  }
  .salary {
    cursor: pointer;
    margin: 24px 0;
    .item {
      padding: 24px;
      text-align: center;
      border: 1px solid #ccc;
      border-radius: 4px;
    }
  }
}
</style>
